<template>
  <div class="home-container layout-pd">
    <el-row :gutter="15" class="home-card-one mb15">
      <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-for="(v, k) in state.homeOne" :key="k"
        :class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }">
        <div class="home-card-item flex">
          <div class="flex-margin flex w100" :class="` home-one-animation${k}`">
            <div class="flex-auto">
              <span class="font20">{{ v.num1 }}</span>
              <div class="mt20">{{ v.num2 }}</div>
            </div>
            <div class="home-card-item-icon flex"
              :style="{ backgroundColor: `${v.color1}`, width: `80px`, height: `80px` }">
              <img :src="v.num4" alt="" class="flex-margin font32"
                :style="{ color: `var(${v.color3})`, width: `65%` }" />
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-two mb15">
      <el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16">
        <div class="home-card-item">
          <div>
            <div class="caption">
              <div class="name">今日兑换记录</div>
              <div class="but" @click="
                () => {
                  (this as any).$router.push('/jifen/score');
                }
              ">
                更多
              </div>
            </div>
          </div>
          <div class="tables">
            <el-table style="width: 100%" :data="datas" height="300px">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="序号" width="120" property="id" align="center" />
              <el-table-column property="name" label="用户名称" width="120" align="center" />
              <el-table-column property="title" label="商品名称" align="center" />
              <el-table-column property="num" label="数量" align="center" />
              <el-table-column property="createtime" label="兑换时间" align="center" />
              <el-table-column label="状态" :formatter="statusFormatter" align="center" />
            </el-table>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media">
        <div class="home-card-item">
          <div style="height: 100%" ref="homePieRef"></div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-three">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="home-media">
        <div class="home-card-item">
          <div style="height: 100%" ref="homeBarRefs"></div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="15" class="home-card-three">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="home-media">
        <div class="home-card-item">
          <div style="height: 100%" ref="homeBarRef"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="home">
import { reactive, onMounted, ref, watch, nextTick, markRaw, onActivated, onUnmounted } from "vue";
import * as echarts from "echarts";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "/@/stores/themeConfig";
import { useTagsViewRoutes } from "/@/stores/tagsViewRoutes";
import { homeData, exchange } from "/@/api/login/index";
import "/src/css/home.css";

// 定义DOM引用和数据变量
const homePieRef = ref();
const homeBarRefs = ref(); // 最下方柱状图
const homeBarRef = ref();  // 中间柱状图
const arr = ref<any>({});
const datas = ref<any[]>([]);
const dataTop = ref<any[]>([]);
const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);

// 格式化状态列显示
const statusFormatter = (row: any, column: any, cellValue: any) => {
  return cellValue === 1 ? "待兑换" : "已兑换";
};

// 初始化所有图表
const initAllCharts = () => {
  if (!arr.value.amount) return; // 确保数据已加载

  initPieChart();
  initLineChart();
  initBarChart();
};

// 页面挂载完成后执行
onMounted(() => {
  // 获取兑换记录数据
  exchange()
    .then((res) => {
      if (Array.isArray(res.data)) {
        datas.value = res.data;
      }
    })
    .catch(() => {
      // ElMessage.error('获取兑换记录失败');
      // console.error(err);
    })

  // 获取首页统计数据
  homeData()
    .then((res) => {
      arr.value = res.data || {};
      dataTop.value = res.data?.top || [];

      // 数据处理：格式化图表所需数据（修复越界问题）
      const amount = arr.value.amount || {};
      // 解构各数组并设置默认空数组，避免undefined
      const { food = [], lark = [], room = [], scenic = [] } = amount;
      // 取最小长度作为循环上限，防止越界
      const maxLength = Math.min(food.length, lark.length, room.length, scenic.length);

      for (let i = 0; i < maxLength; i++) {
        // 处理每个数组元素前先检查存在性
        if (food[i]) {
          food[i].stationName = food[i].month;
          food[i].value = food[i].total_money;
        }
        if (lark[i]) {
          lark[i].stationName = lark[i].month;
          lark[i].value = lark[i].total_money;
        }
        if (room[i]) {
          room[i].stationName = room[i].month;
          room[i].value = room[i].total_money;
        }
        if (scenic[i]) {
          scenic[i].stationName = scenic[i].month;
          scenic[i].value = scenic[i].total_money;
        }
      }

      // 更新卡片数据
      dataTop.value.forEach((item, i) => {
        if (state.homeOne[i]) {
          state.homeOne[i].num1 = item.value;
        }
      });

      // 数据处理完成后初始化图表
      nextTick(() => {
        initAllCharts();
      });
    })
    .catch(() => {
      // ElMessage.error('获取统计数据失败');
      // console.error(err);
    })

  // 初始化图表响应式处理
  initEchartsResize();
});

// 定义页面状态数据
const state = reactive({
  global: {
    homeChartOne: null,
    homeChartTwo: null,
    homeCharThree: null,
    dispose: [null, "", undefined],
  } as any,
  homeOne: [
    {
      num1: "24",
      num2: "美食",
      num4: "/images/burger.png",
      color1: "#ECF5FF",
      color2: "--next-color-primary-lighter",
      color3: "--el-color-primary",
    },
    {
      num1: "13",
      num2: "娱乐",
      num4: "/images/game.png",
      color1: "#F0F9EB",
      color2: "--next-color-success-lighter",
      color3: "--el-color-success",
    },
    {
      num1: "24",
      num2: "酒店",
      num4: "/images/sleep.png",
      color1: "#FDF6EC",
      color2: "--next-color-warning-lighter",
      color3: "--el-color-warning",
    },
    {
      num1: "7",
      num2: "景区",
      num4: "/images/gourmet.png",
      color1: "#FEF0F0",
      color2: "--next-color-danger-lighter",
      color3: "--el-color-danger",
    },
  ],
  homeThree: [],
  myCharts: [] as any[],
  charts: {
    theme: "",
    bgColor: "",
    color: "#303133",
  },
});

// 初始化饼图
const initPieChart = () => {
  // 安全销毁已有图表
  if (state.global.homeChartTwo) {
    state.global.homeChartTwo.dispose();
  }

  if (!homePieRef.value) return; // 确保DOM已挂载

  state.global.homeChartTwo = markRaw(echarts.init(homePieRef.value, state.charts.theme));

  const getname = ["总用户", "已审核", "未审核"];
  const getvalue = [99, 42, 56];
  const data = getname.map((name, i) => ({ name, value: getvalue[i] }));

  const colorList = ["#3C90F7", "#55BFC0", "#5EBE67"];
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: "入驻",
      x: "left",
      textStyle: { fontSize: "20", color: state.charts.color },
    },
    tooltip: { trigger: "item", formatter: "{b} <br/> {c}" },
    graphic: { elements: [] },
    legend: {
      type: "scroll",
      orient: "vertical",
      top: "center",
      itemWidth: 14,
      itemHeight: 14,
      data: getname,
      textStyle: {
        rich: {
          name: {
            fontSize: 20,
            fontWeight: 400,
            width: 200,
            height: 35,
            padding: [0, 0, 0, 60],
            color: state.charts.color,
          },
          rate: {
            fontSize: 15,
            fontWeight: 500,
            height: 35,
            width: 40,
            padding: [0, 0, 0, 30],
            color: state.charts.color,
          },
        },
      },
    },
    series: [
      {
        type: "pie",
        radius: ["105", themeConfig.value.isIsDark ? "0" : "72"],
        center: ["50%", "50%"],
        itemStyle: {
          color: (params: any) => colorList[params.dataIndex],
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {c}'
        },
        labelLine: {
          show: true,
          length: 20,
          length2: 30
        },
        data: data,
      },
    ],
  };

  state.global.homeChartTwo.setOption(option);
  state.myCharts.push(state.global.homeChartTwo);
};

// 初始化中间柱状图
const initLineChart = () => {
  // 安全销毁已有图表
  if (state.global.homeChartOne) {
    state.global.homeChartOne.dispose();
  }

  if (!homeBarRef.value) return; // 确保DOM已挂载

  state.global.homeChartOne = markRaw(
    echarts.init(homeBarRef.value, state.charts.theme)
  );

  const amount = arr.value.amount || {};
  const { food = [], lark = [], room = [], scenic = [] } = amount;

  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: "销售金额",
      x: "left",
      textStyle: { fontSize: "15", color: state.charts.color },
    },
    tooltip: { trigger: "axis" },
    legend: { data: ["美食", "娱乐", "酒店", "景区"], right: 0 },
    grid: { top: 70, right: 80, bottom: 30, left: 80 },
    xAxis: [
      {
        type: "category",
        data: ["1月", "9月", "10月", "11月", ],
        boundaryGap: true,
        axisTick: { show: false },
      },
    ],
    yAxis: [
      {
        name: "",
        nameLocation: "middle",
        nameTextStyle: { padding: [3, 4, 50, 6] },
        splitLine: { show: false, lineStyle: { type: "dashed", color: "#f5f5f5" } },
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: state.charts.color, formatter: "{value} " },
      },
      {
        name: "",
        nameLocation: "middle",
        nameTextStyle: { padding: [50, 4, 5, 6] },
        splitLine: { show: false },
        axisLine: { show: false },
        axisLabel: { show: false },
      },
    ],
    series: [
      {
        name: "美食",
        type: "bar",
        symbolSize: 12,
        yAxisIndex: 0,
        itemStyle: { color: "#FF8000" },
        data: food.map((item: any) => item.value) || [],
      },
      {
        name: "娱乐",
        type: "bar",
        showSymbol: true,
        symbol: "emptyCircle",
        symbolSize: 12,
        yAxisIndex: 0,
        itemStyle: { color: "#3bbc86" },
        data: lark.map((item: any) => item.value) || [],
      },
      {
        name: "酒店",
        type: "bar",
        yAxisIndex: 1,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#FAC954" },
          ]),
        },
        data: room.map((item: any) => item.value) || [],
      },
      {
        name: "景区",
        type: "bar",
        yAxisIndex: 1,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#55BFC0" },
          ]),
        },
        data: scenic.map((item: any) => item.value) || [],
      },
    ],
  };

  state.global.homeChartOne.setOption(option);
  state.myCharts.push(state.global.homeChartOne);
};

// 初始化最下方柱状图
const initBarChart = () => {
  // 安全销毁已有图表
  if (state.global.homeCharThree) {
    state.global.homeCharThree.dispose();
  }

  if (!homeBarRefs.value) return; // 确保DOM已挂载

  state.global.homeCharThree = markRaw(
    echarts.init(homeBarRefs.value, state.charts.theme)
  );

  const amount = arr.value.amount || {};
  const { food = [], lark = [], room = [], scenic = [] } = amount;

  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: "销售量",
      x: "left",
      textStyle: { fontSize: "15", color: state.charts.color },
    },
    tooltip: { trigger: "axis" },
    legend: { data: ["美食", "娱乐", "酒店", "景区"], right: 0 },
    grid: { top: 70, right: 80, bottom: 30, left: 80 },
    xAxis: [
      {
        type: "category",
        data: ["1月", "9月", "10月", "11月", ],
        boundaryGap: true,
        axisTick: { show: false },
      },
    ],
    yAxis: [
      {
        name: "",
        nameLocation: "middle",
        nameTextStyle: { padding: [3, 4, 50, 6] },
        splitLine: { show: true, lineStyle: { type: "dashed", color: "#f5f5f5" } },
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { color: state.charts.color, formatter: "{value} " },
      },
      {
        name: "",
        nameLocation: "middle",
        nameTextStyle: { padding: [50, 4, 5, 6] },
        splitLine: { show: false },
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { show: false },
      },
    ],
    series: [
      {
        name: "美食",
        type: "line",
        symbolSize: 12,
        yAxisIndex: 0,
        itemStyle: { color: "#FF8000" },
        data: food.map((item: any) => item.value) || [],
      },
      {
        name: "娱乐",
        type: "line",
        showSymbol: true,
        symbol: "emptyCircle",
        symbolSize: 12,
        yAxisIndex: 0,
        itemStyle: { color: "#3bbc86" },
        data: lark.map((item: any) => item.value) || [],
      },
      {
        name: "酒店",
        type: "line",
        barWidth: 30,
        yAxisIndex: 1,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(108,80,243,0.3)" },
          ]),
        },
        data: room.map((item: any) => item.value) || [],
      },
      {
        name: "景区",
        type: "line",
        barWidth: 30,
        yAxisIndex: 1,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "rgba(108,80,243,0.3)" },
          ]),
        },
        data: scenic.map((item: any) => item.value) || [],
      },
    ],
  };

  state.global.homeCharThree.setOption(option);
  state.myCharts.push(state.global.homeCharThree);
};

// 批量设置 echarts resize
const initEchartsResizeFun = () => {
  nextTick(() => {
    state.myCharts.forEach(chart => {
      chart && chart.resize();
    });
  });
};

// 初始化图表响应式处理
const initEchartsResize = () => {
  window.addEventListener("resize", initEchartsResizeFun);
};

// 页面激活时重绘图表
onActivated(() => {
  initEchartsResizeFun();
});

// 监听 tagsview 全屏变化，重新 resize 图表
watch(
  () => isTagsViewCurrenFull.value,
  () => {
    initEchartsResizeFun();
  }
);

// 监听深色主题变化
watch(
  () => themeConfig.value.isIsDark,
  (isIsDark) => {
    nextTick(() => {
      state.charts.theme = isIsDark ? "dark" : "";
      state.charts.bgColor = isIsDark ? "transparent" : "";
      state.charts.color = isIsDark ? "#dadada" : "#303133";

      // 延迟初始化图表，确保主题已应用
      setTimeout(() => {
        initAllCharts();
      }, 300);
    });
  },
  { deep: true, immediate: true }
);

// 组件卸载时销毁图表
onUnmounted(() => {
  window.removeEventListener("resize", initEchartsResizeFun);
  state.myCharts.forEach(chart => {
    chart && chart.dispose();
  });
  state.myCharts = [];
});
</script>

<style scoped lang="scss">
$homeNavLengh: 8;

.home-container {
  overflow: hidden;

  .home-card-one,
  .home-card-two,
  .home-card-three {
    .home-card-item {
      width: 100%;
      height: 130px;
      border-radius: 4px;
      transition: all ease 0.3s;
      padding: 20px;
      overflow: hidden;
      background: var(--el-color-white);
      color: var(--el-text-color-primary);
      border: 1px solid var(--next-border-color-light);

      &:hover {
        box-shadow: 0 2px 12px var(--next-color-dark-hover);
        transition: all ease 0.3s;
      }

      &-icon {
        width: 70px;
        height: 70px;
        border-radius: 100%;
        flex-shrink: 1;

        i {
          color: var(--el-text-color-placeholder);
        }
      }

      &-title {
        font-size: 15px;
        font-weight: bold;
        height: 30px;
      }
    }
  }

  .home-card-one {
    @for $i from 0 through 3 {
      .home-one-animation#{$i} {
        opacity: 0;
        animation-name: error-num;
        animation-duration: 0.5s;
        animation-fill-mode: forwards;
        animation-delay: calc($i/4) + s;
      }
    }
  }

  .home-card-two,
  .home-card-three {
    .home-card-item {
      height: 400px;
      width: 100%;
      overflow: hidden;

      .home-monitor {
        height: 100%;

        .flex-warp-item {
          width: 25%;
          height: 111px;
          display: flex;

          .flex-warp-item-box {
            margin: auto;
            text-align: center;
            color: var(--el-text-color-primary);
            display: flex;
            border-radius: 5px;
            background: var(--next-bg-color);
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: var(--el-color-primary-light-9);
              transition: all 0.3s ease;
            }
          }

          @for $i from 0 through $homeNavLengh {
            .home-animation#{$i} {
              opacity: 0;
              animation-name: error-num;
              animation-duration: 0.5s;
              animation-fill-mode: forwards;
              animation-delay: calc($i/10) + s;
            }
          }
        }
      }
    }

    margin-bottom: 20px;
  }
}

// 定义动画
@keyframes error-num {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>